using System;
using System.IO;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using Microsoft.WindowsCE.Forms;

namespace Cworld2000.GsSyndication.Pocket
{
    public class StreamDownloader
    {
        protected const int BufferSize = 1024;
        private Stream m_downloadStream = null;
        private string m_filename = null;
        protected long m_fileLength = 0;

        public StreamDownloader(Stream downloadStream, string filename) {
            m_downloadStream = downloadStream;
            m_filename = filename;
        }

        public long FileLength
        {
            set
            {
                m_fileLength = value;
            }
            get
            {
                return m_fileLength;
            }
        }

        public void Invoke()
        {
            long downloadedLength = 0;
            long offset;
            byte[] buffer = new byte[BufferSize];
            FileStream fs = new FileStream(m_filename, FileMode.Create);

            DownloadingFileDialog dlg = new DownloadingFileDialog();
            dlg.FileName = Path.GetFileName(m_filename);
            dlg.Value = 0;
            dlg.Show();
            dlg.Focus();
            try
            {
                if (m_fileLength > 0)
                {
                    while (downloadedLength < m_fileLength)
                    {
                        offset = m_downloadStream.Read(buffer, 0, BufferSize);
                        Application.DoEvents();
                        fs.Write(buffer, 0, (int)offset);
                        downloadedLength += offset;
                        if (m_fileLength != 0)
                        {
                            double percent = (downloadedLength / m_fileLength) * 100.0;
                            dlg.Value = (int)percent;
                        }
                        offset = 0;
                    }
                }
            }
            catch (IOException)
            {
            }
            finally
            {
                fs.Close();
            }
            dlg.Hide();
        }
    }
}
